<?php

class BaseDBModel extends CModel
{
    protected $tableName;
    protected $primaryKey;

    public function attributeNames()
    {
    }

    public function __construct($tableName, $primaryKey = 'id')
    {
        //parent::__construct();
        $this->tableName = $tableName;
        $this->primaryKey = $primaryKey;
    }

    public function getCommand($sql = '')
    {
        return Yii::app()->db->createCommand($sql);
    }

    public function get($where, $params = array())
    {
        return $this->getCommand()
            ->from($this->tableName)
            ->where($where, $params)
            ->queryAll();
    }

    public function getOne($where, $params = array())
    {
        return $this->getCommand()
            ->from($this->tableName)
            ->where($where, $params)
            ->limit(1)
            ->queryRow();
    }

    /**
     * @param $columns array
     * @return int
     */
    public function insert($columns)
    {
        $count = $this->getCommand()->insert($this->tableName, $columns);
        return $count == 0 ? 0 : intval($this->getLastInsertID());
    }

    public function update($columns, $conditions='', $params=array())
    {
        return $this->getCommand()->update($this->tableName, $columns, $conditions, $params);
    }

    public function delete($conditions='', $params=array())
    {
        return $this->getCommand()->delete($this->tableName, $conditions, $params);
    }

    public function getOrInsert($columns, $where, $params = array())
    {
        $items = $this->get($where, $params);
        if (count($items) >= 1)
        {
            return intval($items[0][$this->primaryKey]);
        }
        else
        {
            return intval($this->insert($columns));
        }
    }

    /**
     * Gets count rows in table by params
     *
     * @param string $where
     * @param array $params
     * @return int
     */
    public function count($where='', $params = array())
    {
        $where = trim($where);

        $row = $this->getCommand()
            ->from($this->tableName)
            ->select('count(*) as count');

        if (($where!=='') AND (is_array($params))) {
            $row->where($where, $params);
        }

        $row = $row->queryRow();
        return intval($row['count']);

    }

    public function getLastInsertID()
    {
        return Yii::app()->db->lastInsertID;
    }

}
?>